package com.ssm.web.controller;

import com.ssm.entity.Dept;
import com.ssm.entity.Emp;
import com.ssm.entity.EmpQueryObject;
import com.ssm.entity.PageResult;
import com.ssm.service.DeptService;
import com.ssm.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    //查看localhost:8088/employee/list
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("empQuery") EmpQueryObject empQuery) {
        PageResult<Emp> pageResult = empService.query(empQuery);
        model.addAttribute("pageResult", pageResult);
        List<Dept> deptList = deptService.selAll();
        model.addAttribute("deptList", deptList);
        return "employee/list";
    }

    //删除localhost:8088/employee/delete?id=xxx
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            empService.delete(id);
        }
        return "redirect:/employee/list";//返回上面的查询所有list方法
    }

    //新增localhost:8088/employee/input
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Dept> deptList = deptService.selAll();
        model.addAttribute("deptList", deptList);
        if (id != null) {
            //查询原视数据用于封装
            Emp emp = empService.sqlById(id);
            model.addAttribute("emp", emp);
        }
        return "employee/input";
    }

    //处理localhost:8088/employee/saveOrUpdate
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Emp emp) {
        if (emp.getId() != null) {
            empService.update(emp);
        } else {
            empService.save(emp);
        }
        return "redirect:/employee/list";
    }
}
